package com.retlife.tvshow.serial_port

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.hardware.usb.UsbManager
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.retlife.tvshow.R
import com.retlife.tvshow.global.RunningContext
import com.retlife.tvshow.serial_port.bike.SerialBikeManager
import com.retlife.tvshow.serial_port.bike.model.BikeData
import java.io.File
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.ThreadFactory
import java.util.concurrent.TimeUnit
import kotlin.random.Random

/**
 * @author zzx
 */
class SerialPortService : Service() {
    private lateinit var scheduledExecutorService: ScheduledExecutorService

    //    private var serialBikeManager: SerialBikeManager? = null
    private var scheduledFuture: ScheduledFuture<*>? = null
    private var isInit: Boolean = true
    private val serialBikeManagerList = mutableListOf<SerialBikeManager>()
    private lateinit var hardWareBinder: HardWareBinder
    override fun onCreate() {
        super.onCreate()
        val threadFactory = ThreadFactory { Thread(it, TAG) }
        scheduledExecutorService = ScheduledThreadPoolExecutor(2, threadFactory)
        setForeground()
        initSerialPort()
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    private fun initSerialPort() {
        val serialFiles: List<String> = BaseSerialManage.serialFiles
        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        val deviceList = usbManager.deviceList
        val addressList = mutableListOf<String>()
       /* for (i in 0 until RunningContext.maxConnect) {
            val serialBikeManager = SerialBikeManager(addressList[i])
            serialBikeManagerList.add(serialBikeManager)
            scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(object : Runnable {
                override fun run() {
                    isInit = true
                    if (!serialBikeManager.isOpen) {
                        if (!serialBikeManager.open()) {
                            Log.i(javaClass.simpleName, "bike串口打开失败")
                            isInit = false
                        }
                    }
                    hardWareBinder.initState(isInit)
                    if (isInit) {
                        Log.i(javaClass.simpleName, "串口初始化完成")
                        scheduledFuture!!.cancel(true)
                        scheduledFuture = null
                    }
                }
            }, 0, 5, TimeUnit.SECONDS)
        }*/

        //此处为模拟数据
        for (i in 0 until RunningContext.maxConnect) {
            if (i >= RunningContext.bikeDataList.size)
                RunningContext.bikeDataList.add(i, BikeData())
        }
      scheduledFuture=  scheduledExecutorService.scheduleAtFixedRate(
            {
                for (i in 0 until RunningContext.maxConnect) {
                    RunningContext.bikeDataList[i].speed = (Random.nextInt(80, 91))
                    RunningContext.bikeDataList[i].torqueAverage = (Random.nextInt(10, 19))
                    RunningContext.bikeDataList[i].isActive = (Random.nextBoolean())

                }

            }, 1, 2000, TimeUnit.MILLISECONDS
        )
    }

    override fun onBind(intent: Intent): IBinder {
        hardWareBinder = HardWareBinder()
        return hardWareBinder
    }


    interface HardwareInitListener {
        fun initFinish(b: Boolean)
    }

    inner class HardWareBinder : Binder() {

        fun initState(b: Boolean) {
            hardwareInitListener?.initFinish(b)
        }

        val service: SerialPortService
            get() {
                return this@SerialPortService
            }
        var hardwareInitListener: HardwareInitListener? = null
    }

    private fun setForeground() {
        Log.i(TAG, "-------------onCreate")
        val context: Context = this
        val notificationManager: NotificationManager? =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager?
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, "notification_id")
        builder.setSmallIcon(R.mipmap.ic_launcher)
        builder.setContentTitle("串口服务").setContentText("运行中")
        builder.setLargeIcon(
            BitmapFactory.decodeResource(
                resources,
                R.mipmap.ic_launcher_round
            )
        )
        // 8.0设置Notification的Channel_ID,否则不能正常显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id")
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id")
            val channel =
                NotificationChannel("notification_id", TAG, NotificationManager.IMPORTANCE_HIGH)
            assert(notificationManager != null)
            notificationManager!!.createNotificationChannel(channel)
        }
        //启用前台服务 其目的是为了保活 提高Service的优先级
        startForeground(0, builder.build())
//        notificationManager!!.notify(1, builder.build())
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "-------------onDestroy")
        if (scheduledFuture != null) {
            scheduledFuture!!.cancel(true)
        }
        scheduledExecutorService.shutdown()
        /*        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this,HardWareManage.class);
        PendingIntent pendingIntent = PendingIntent.getService(this,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.set(AlarmManager.RTC,System.currentTimeMillis() + 200,pendingIntent);*/
    }


    companion object {
        private const val TAG: String = "SerialPortService"

    }

}
